<?php

$requestData = json_decode(file_get_contents('php://input'), true);

if (isset($requestData['url'])){
	$url = $requestData['url'];
	header('Content-Type: application/json');
	echo json_encode(['url' => $url, 'data' => get_page_content($url)]);
}

function get_page_content($url)
{
	$dom = new DOMDocument();
	@$dom->loadHTML(file_get_contents($url));
	$xpath = new DOMXPath($dom);
	$title_elements = $xpath->query('//html/body/div[2]/section[1]/div[3]/div/div/div[2]/div/h1');
	$sales_url_elements = $xpath->query('//html/body/div[2]/section[2]/div/div[1]/div/section[1]/div/div[1]/div/div/div/div/a');
	$featured_image_elements = $xpath->query('//*[@id="featured-image"]/div/img');
	$version_elements = $xpath->query('//html/body/div[2]/section[2]/div/div[2]/div/section[4]/div/div/div/div[2]/div/ul/li[1]/span[2]');
	$virus_report_elements = $xpath->query('//html/body/div[2]/section[2]/div/div[2]/div/section[3]/div/div/div/div[2]/div/div/div/div[2]/div/p[3]/a');
	$description_elements = $xpath->query('//html/body/div[2]/section[2]/div/div[1]/div/section[2]/div/div/div/div[2]/div');
	$metaDescription = $xpath->query('//meta[@name="description"]');


	if ($title_elements->length > 0) {
		$element = $title_elements->item(0); // Get the first matching element
		$title = $element->textContent; // Get the text content of the element
	}

	if($sales_url_elements->length > 0){
		$element = $sales_url_elements->item(0);
		$sales_url = $element->getAttribute('href');
	}

	if($featured_image_elements->length > 0){
		$element = $featured_image_elements->item(0);
		$featured_image = $element->getAttribute('data-src');
	}

	if($version_elements->length > 0){
		$element = $version_elements->item(0);
		$version = $element->textContent;
		$version = str_replace('Version ', '', $version);
	}

	if($virus_report_elements->length > 0){
		$element = $virus_report_elements->item(0);
		$virus_report = $element->getAttribute('href');
	}

	if($description_elements->length > 0){
		$element = $description_elements->item(0);
		$description = $element->textContent;
	}

	$descriptionContent = '';
	if ($metaDescription->length > 0) {
		$descriptionContent = $metaDescription->item(0)->getAttribute('content');
	}

	return [
		    "title" => $title??'',
	        "sales_url" => $sales_url??'',
	        "featured_image" => $featured_image??'',
	        "version" => $version??'',
	        "virus_report" => $virus_report??'',
	        "description" => trim($description??''),
		    "meta_description" => trim($descriptionContent)
	];
}